// 合并后的云函数代码（新增消息存储和广播逻辑）
const cloud = require('wx-server-sdk');
const WebSocket = require('ws');

cloud.init();
const db = cloud.database();
const _ = db.command;

const clients = new Map(); // 存储房间ID -> Set(WebSocket客户端)

exports.main = async (event, context) => {
    console.log('云函数被触发，接收到的 event 对象:', event);
    console.log('云函数被触发，接收到的 context 对象:', context);

    const { path } = event;
    if (path === '/WebSocketServer') {
        console.log('请求路径匹配 /WebSocketServer，开始处理 WebSocket 连接');
        const wss = new WebSocket.Server({ noServer: true });

        const server = {
            upgrade: (req, socket, head) => {
                console.log('收到 HTTP 升级请求，开始处理升级');
                wss.handleUpgrade(req, socket, head, (ws) => {
                    console.log('HTTP 升级成功，触发 WebSocket 连接事件');
                    wss.emit('connection', ws, req);
                });
            }
        };

        wss.on('connection', (ws, req) => {
            console.log('有新的 WebSocket 连接建立');
            const url = new URL(req.url, `http://${req.headers.host}`);
            const roomId = url.searchParams.get('roomId');
            console.log('从 URL 中获取到的 roomId:', roomId);

            if (roomId) {
                if (!clients.has(roomId)) {
                    console.log(`房间 ${roomId} 首次有客户端连接，创建新的客户端集合`);
                    clients.set(roomId, new Set());
                }
                clients.get(roomId).add(ws);
                console.log(`客户端已加入房间 ${roomId}，当前房间客户端数量:`, clients.get(roomId).size);
            }

            ws.on('message', async (message) => {
                console.log('收到客户端消息:', message);
                try {
                    const data = JSON.parse(message);
                    console.log('解析后的消息数据:', data);
                    if (data.action === 'sendMessage') {
                        const { roomId, content, senderId } = data;

                        // 1. 验证用户是否属于该房间（可选）
                        console.log(`开始验证用户 ${senderId} 是否属于房间 ${roomId}`);
                        const isMember = await db.collection('chatroomMembers')
                           .where({ roomId, userId: senderId })
                           .count();
                        console.log(`用户 ${senderId} 在房间 ${roomId} 的成员验证结果，成员数量:`, isMember.total);
                        if (isMember.total === 0) {
                            console.log(`用户 ${senderId} 没有权限向房间 ${roomId} 发送消息，返回权限不足错误`);
                            return ws.send(JSON.stringify({ error: '权限不足' }));
                        }

                        // 2. 消息存入数据库
                        console.log(`开始将消息存入数据库，房间 ID: ${roomId}，发送者 ID: ${senderId}，消息内容: ${content}`);
                        const messageRes = await db.collection('messages').add({
                            data: {
                                roomId,
                                senderId,
                                content,
                                sendTimeTs: Date.now(),
                                likeCount: 0,
                                collectCount: 0,
                                showTime: true
                            }
                        });
                        console.log('消息已成功存入数据库，消息 ID:', messageRes._id);

                        // 3. 广播消息给房间内的其他客户端
                        const roomClients = clients.get(roomId);
                        if (roomClients) {
                            console.log(`开始广播消息给房间 ${roomId} 内的其他客户端，当前房间客户端数量:`, roomClients.size);
                            roomClients.forEach(client => {
                                if (client!== ws && client.readyState === WebSocket.OPEN) {
                                    console.log('向客户端发送消息');
                                    client.send(JSON.stringify({
                                        type: 'message',
                                        data: {
                                            messageId: messageRes._id,
                                            roomId,
                                            senderId,
                                            content,
                                            sendTimeTs: Date.now()
                                        }
                                    }));
                                }
                            });
                        }
                    }
                } catch (e) {
                    console.error('消息处理失败:', e);
                    ws.send(JSON.stringify({ error: '服务器错误' }));
                }
            });

            ws.on('close', () => {
                console.log('WebSocket 连接关闭');
                if (roomId) {
                    const roomClients = clients.get(roomId);
                    if (roomClients) {
                        roomClients.delete(ws);
                        console.log(`客户端已从房间 ${roomId} 移除，当前房间客户端数量:`, roomClients.size);
                        if (roomClients.size === 0) {
                            clients.delete(roomId);
                            console.log(`房间 ${roomId} 已无客户端，删除房间客户端集合`);
                        }
                    }
                }
            });
        });

        return {
            statusCode: 101,
            headers: {
                'Upgrade': 'websocket',
                'Connection': 'Upgrade'
            },
            body: '',
            isBase64Encoded: false
        };
    }

    console.log('请求路径不匹配 /WebSocketServer，返回 404 错误');
    return {
        statusCode: 404,
        body: 'Not Found'
    };
};